import { Component, Vue } from 'vue-facing-decorator';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form';
import { formProps } from '@2/views/home/system/account/account.data';
import { computed, ref, unref } from 'vue';
import { getDeptList } from '@/api/demo/system';

/**
 * @program: microservice-central-portal
 * @description: 系统账号管理
 * @author: baiHoo.chen
 * @create: 2022年5月24日
 **/
@Component({
  name: 'AccountModal',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],
})
export default class AccountModal extends Vue {
  formReturn = useForm(formProps);
  modelReturn = useModalInner(this.callback);
  registerForm = this.formReturn[0];
  registerModal = this.modelReturn[0];
  isUpdate = ref(true);
  rowId = ref('');
  getTitle = computed(() => (!unref(this.isUpdate) ? '新增账号' : '编辑账号'));
  /**
   * 提交
   */
  async handleSubmit() {
    const { setModalProps, closeModal } = this.modelReturn[1];
    const { validate } = this.formReturn[1];
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      console.log(values);
      closeModal();
      this.$emit('success', {
        isUpdate: unref(this.isUpdate),
        values: { ...values, id: this.rowId.value },
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  /**
   * 回调
   * @param data
   */
  async callback(data: Recordable) {
    const { setFieldsValue, updateSchema, resetFields } = this.formReturn[1];
    const { setModalProps } = this.modelReturn[1];
    await resetFields();
    setModalProps({ confirmLoading: false });
    this.isUpdate.value = !!data?.isUpdate;
    if (unref(this.isUpdate)) {
      this.rowId.value = data.record.id;
      await setFieldsValue({
        ...data.record,
      });
    }
    const treeData = await getDeptList();
    await updateSchema([
      {
        field: 'pwd',
        show: !unref(this.isUpdate),
      },
      {
        field: 'dept',
        componentProps: { treeData },
      },
    ]);
  }
}
